package com.zyy.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyy.seckill.entity.*;
import com.zyy.seckill.exception.GlobalException;
import com.zyy.seckill.mapper.OrderMapper;
import com.zyy.seckill.service.IGoodsService;
import com.zyy.seckill.service.IOrderService;
import com.zyy.seckill.service.ISeckillGoodsService;
import com.zyy.seckill.service.ISeckillOrderService;
import com.zyy.seckill.utils.MD5Util;
import com.zyy.seckill.utils.UUIDUtil;
import com.zyy.seckill.vo.GoodsVo;
import com.zyy.seckill.vo.OrderDetailVo;
import com.zyy.seckill.vo.RespEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zyy
 * @since 2021-10-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    IGoodsService goodsService;


    /**
     *          秒杀
     *
     * @param user
     * @param goodsVo
     * @return
     */
    @Transactional //处理并发事务的注解
    @Override
    public Order seckill(User user, GoodsVo goodsVo) {

        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 秒杀减库存
        SeckillGoods goods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>()
                .eq("goods_id", goodsVo.getId()));

        goods.setStockCount(goods.getStockCount() - 1);
//        seckillGoodsService.updateById(goods);
        // 秒杀减库存 --->  处理超卖现象
        boolean seckillResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().setSql("stock_count =stock_count-1")
                .eq("goods_id", goodsVo.getId())
                .gt("stock_count", 0));
//        if (!seckillResult) {
//            return null;
//        }
        if (goods.getStockCount()<1){
            // 在redis中标记数据库中没有了库存
            valueOperations.set("isStockEmpty:"+goodsVo.getId(),"0");
        }


        // 封装订单参数
        Order order = new Order();
        order.setUserId(user.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsId(goodsVo.getId());
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goodsVo.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());

        // 生成订单  --> 插入之后会自动主键返回封装到 order中
        orderMapper.insert(order);

        // 生成秒杀订单
        SeckillOrder seckillOrder =
                new SeckillOrder();

        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrderService.save(seckillOrder);

        // 把更新的结果存在redis中,使用redis对重复购买的订单进行拦截
        redisTemplate.opsForValue().set("order:" + user.getId() + ":" + goodsVo.getId(), seckillOrder);

        return order;
    }

    /**
     * 订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId == null) {
            throw new GlobalException(RespEnum.SESSION_ERROR);
        }
        Order order = orderMapper.selectById(orderId);

        GoodsVo goodsVo = goodsService.findGoodsVoById(order.getGoodsId());
        OrderDetailVo detailVo = new OrderDetailVo();
        detailVo.setOrder(order);
        detailVo.setGoodsVo(goodsVo);
        return detailVo;
    }
    /**
     * 创建用户请求返回地址
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, String goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        ValueOperations valueOperations = redisTemplate.opsForValue();

//        把接口返回地址存在60s的redis中去
        valueOperations.set("seckillPath:"+user.getId()+":"+goodsId,str,60, TimeUnit.SECONDS);

        return str;
    }

    /**
     *      验证码校验
     * @param user
     * @param goodsId
     * @param captcha
     * @return
     */
    @Override
    public boolean checkCaptcha(User user, String goodsId, String captcha) {
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("capche:" + user.getId() + ":" + goodsId);

        return captcha.equals(redisCaptcha);
    }

    /**
     *
     * @param user
     * @param goodsId
     * @param path
     * @return
     */
    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        if (user == null || !StringUtils.hasLength(path)){
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);

        if (!path.equals(redisPath)){
            return false;
        }
        return true;
    }
}
